package com.supermap.localization.util;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DBUtil {

    public static SqlSession getSqlSession() throws Exception {
        String resource = "MyBatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        Properties properties = PropertiesHelper.loadProperties(new File("localizationTool.properties").getAbsolutePath());
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, properties);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        initDB(sqlSession);
        return sqlSession;
    }

    public static void closeSqlSession() throws Exception {
        getSqlSession().close();
    }

    public static void initDB(SqlSession sqlSession) {
        Object exist = sqlSession.selectOne("DBInit.existTable", "sample");
        if (Integer.parseInt(exist.toString()) == 0) {
            sqlSession.update("DBInit.createSampleTable");
        }
        exist = sqlSession.selectOne("DBInit.existTable", "sampleLocation");
        if (Integer.parseInt(exist.toString()) == 0) {
            sqlSession.update("DBInit.createSampleLocationTable");
        }
        sqlSession.commit();
    }

}
